package vcproj2cmake;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

public class Solution {

	public String name;
	public File file;
	public ArrayList<Project> projects = new ArrayList<Project>();
	public HashMap<String, File> pathMap = new HashMap<String, File>();
	public File rootPath;
	
	public String makeVariable(Project p, String pref, String str){
		if (str == null)
			return str;
		String incList[] = str.split(";");
		if (incList.length == 1)
			incList = str.split(" ");
		for (int k = 0; k < incList.length; k++){
			if (incList[k].contains("$")){
				incList[k] = "";
				continue;
			}
			File f = new File(p.projFile.getParent()+"/"+incList[k]);
			if (!f.exists()){
				System.err.println("Could not find dependencie Path: "+f.toString());
				System.exit(1);
			}
			String varName = f.getName();
			if (varName.toLowerCase().equals("include")){
				varName = f.getParentFile().getName();
			}
			if (varName.toLowerCase().equals("lib"))
				varName = f.getParentFile().getName();
			
			if (varName.equals(p.Name)){
				incList[k] += ";";
				continue;
			}
			varName = "PATH_TO_"+pref+"_"+varName;
			if (!pathMap.containsKey(varName))
				pathMap.put(varName, f);
			incList[k] = "${"+varName+"};";
		}
		String out = "";
		for (int i = 0; i < incList.length; i++)
			out+= incList[i];
		return out;
	}
	public void makePaths(){
		for (int i = 0; i < projects.size(); i++){
			Project p = projects.get(i);
			for (int j = 0; j < p.configurations.size(); j++){
				Configuration c = p.configurations.get(j);
				c.AdditionalIncludeDirectories = makeVariable(p, "INCLUDE", c.AdditionalIncludeDirectories);
				c.AdditionalLibraryDirectories = makeVariable(p, "LIB", c.AdditionalLibraryDirectories);
			}
		}
	}
	public void updateReferences() {
		for (int i = 0; i < projects.size(); i++){
			Project p = projects.get(i);
			for (int j = 0; j < p.references.size(); j++){
				References r = p.references.get(j);
				for (int k = 0; k < projects.size(); k++){
					if (projects.get(k).ProjectGUID.equals(r.ReferencedProjectIdentifier))
						r.name = projects.get(k).Name;
				}
			}
		}
	}
	public HashSet<String> getConfigurations() {
		HashSet<String> set = new HashSet<String>();
		for (int i = 0; i < this.projects.size(); i++){
			for (int j = 0; j < projects.get(i).configurations.size(); j++){
				set.add(projects.get(i).configurations.get(j).name);
			}
		}
		return set;
	}
}
